package org.hefan.hrm.service.impl;

import org.hefan.hrm.client.LoginUserClient;
import org.hefan.hrm.client.ThirdPartyServiceClient;
import org.hefan.hrm.domain.LoginUser;
import org.hefan.hrm.domain.VipBase;
import org.hefan.hrm.domain.VipUser;
import org.hefan.hrm.dto.RegisterDto;
import org.hefan.hrm.exception.ValidUtil;
import org.hefan.hrm.mapper.VipBaseMapper;
import org.hefan.hrm.mapper.VipUserMapper;
import org.hefan.hrm.service.IVipBaseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.hefan.hrm.util.AjaxResult;
import org.hefan.hrm.util.BitStatesUtils;
import org.hefan.hrm.util.UserConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author HeFan
 * @since 2022-01-13
 */
@Service
public class VipBaseServiceImpl extends ServiceImpl<VipBaseMapper, VipBase> implements IVipBaseService {

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Autowired
    private LoginUserClient loginUserClient;

    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Autowired
    private VipUserMapper vipUserMapper;

    @Override
    @Transactional
    public AjaxResult register(RegisterDto registerDto) {
        //1 校验 null+短信验证码+用户检验
        HashMap<String, String> params = new HashMap<>();
        params.put("key", UserConstants.REGISTER_CODE_PREFIX + registerDto.getMobile());
        params.put("code", registerDto.getSmsCode());
        AjaxResult result = thirdPartyServiceClient.verifySmsCode(params);
        ValidUtil.assertTrue(result.isSuccess(), result.getMessage());

        //2 远程调用hrm-auth保存loginUser并获取到loginId
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(registerDto.getMobile());
        loginUser.setPassword(registerDto.getPassword());
        loginUser.setType(1);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        ValidUtil.assertTrue(ajaxResult.isSuccess(), ajaxResult.getMessage());
        Long LoginId = Long.valueOf(ajaxResult.getResultObj().toString());

        //3 保存vipBase，vipUser
        VipBase vipBase = new VipBase();
        vipBase.setPassword(registerDto.getPassword());
        vipBase.setNickName(registerDto.getMobile());
        vipBase.setPhone(registerDto.getMobile());

        long states = BitStatesUtils.OP_REGISTED;
        states = BitStatesUtils.addState(states, BitStatesUtils.OP_ACTIVED);
        states = BitStatesUtils.addState(states, BitStatesUtils.OP_AUTHED_PHONE);
        vipBase.setBitState(states);
        vipBase.setLoginId(LoginId);
        vipBaseMapper.insert(vipBase);

        VipUser vipUser = new VipUser();
        vipUser.setVipId(vipBase.getId());
        vipUserMapper.insert(vipUser);

        return AjaxResult.me();
    }
}
